<template>
  <el-dialog
    width="500px"
    v-bind="$attrs"
    @close="handleClose"
    @opened="handleOpened"
  >
    <el-form
      v-show="!ramKey"
      ref="showForm"
      :model="showForm"
      :rules="rules"
      label-width="auto"
      size="small"
      @submit.prevent.native
    >
      <el-form-item :label="$t('system.ram.password')" prop="operPassword">
        <el-input
          v-model="showForm.operPassword"
          type="password"
          @blur="() => (showForm.operPassword = showForm.operPassword.trim())"
        />
      </el-form-item>
      <el-form-item :label="$t('system.ram.captcha')" prop="code">
        <el-input v-model="showForm.code" style="width: 180px" />
        <button>
          <img
            ref="img"
            style="height: 40px; margin-left: 16px; cursor: pointer"
            @click="getCaptcha"
          />
        </button>
      </el-form-item>
    </el-form>
    <el-row v-show="ramKey" class="mx-6">
      <el-col :span="21">
        <el-input v-model="ramKey" :readonly="true" size="small" />
      </el-col>
      <el-col :span="2" class="mt-2 ml-1">
        <i
          class="el-icon-document-copy cursor-pointer hover:text-blue-1"
          style="font-size: 20px"
          @click="copyKey()"
        />
      </el-col> </el-row
    ><template #footer>
      <span class="dialog-footer">
        <el-button v-show="!ramKey" size="small" @click="handleClose">{{
          $t('common.cancel')
        }}</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="confirmLoading"
          @click="resetRamKey"
        >
          {{ $t('common.confirm') }}
        </el-button>
      </span></template
    >
  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  props: ['userId'],
  data() {
    return {
      ramKey: '',
      confirmLoading: false,
      captchaImgSrc: '',
      showForm: {
        userId: null,
        operPassword: '',
        code: ''
      },
      rules: {
        operPassword: [
          {
            required: true,
            message: this.$t('system.ram.validate_require'),
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: this.$t('system.ram.validate_require'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    copyKey() {
      var textarea = document.createElement('textarea')
      textarea.value = this.ramKey
      // 添加input标签
      document.body.appendChild(textarea)
      // 选中input标签
      textarea.select()
      // 执行复制
      document.execCommand('copy')
      // 成功提示信息
      this.$message.success('Copy Success!')
      // 移除input标签
      document.body.removeChild(textarea)
    },
    getCaptcha() {
      const prefix = import.meta.env.VITE_APP_BASE_API
      this.captchaImgSrc =
        prefix +
        '/online/authorization/auth/verify/code/password/self/check?ramUserId=' +
        this.userId +
        '&time=' +
        new Date().getTime()

      Object.defineProperty(Image.prototype, 'captchaImgSrc', {
        writable: true,
        enumerable: true,
        configurable: true
      })

      const img = this.$refs.img
      const request = new XMLHttpRequest()
      request.responseType = 'blob'
      request.open('get', this.captchaImgSrc, true)
      // 这里带上请求头

      request.setRequestHeader('WEB-TOKEN', getToken())
      request.onreadystatechange = (e) => {
        if (
          request.readyState == XMLHttpRequest.DONE &&
          request.status == 200
        ) {
          img.src = URL.createObjectURL(request.response)
          img.onload = () => {
            URL.revokeObjectURL(img.src)
          }
        }
      }
      request.send(null)
    },
    handleClose() {
      this.ramKey = ''
      this.confirmLoading = false
      this.$refs['showForm'].resetFields()
      this.$emit('update:model-value', false)
    },
    handleOpened() {
      this.getCaptcha()
    },
    resetRamKey() {
      if (this.ramKey) {
        this.handleClose()
      } else {
        this.$refs['showForm'].validate((valid) => {
          if (valid) {
            this.confirmLoading = true
            this.showForm.userId = this.userId
            this.$store
              .dispatch('user/resetRamKey', this.showForm)
              .then((res) => {
                this.ramKey = res.password
              })
              .catch(this.$confirmError)
              .finally(() => {
                this.confirmLoading = false
                this.getCaptcha()
                this.showForm.code = ''
                this.showForm.operPassword = ''
              })
          }
        })
      }
    }
  }
}
</script>

<style>
</style>
